package com.chen.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.common.Result;
import com.chen.mapper.UserMapper;
import com.chen.pojo.User;
import com.chen.pojo.bean.UserInfo;
import com.chen.service.LoginService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
@SuppressWarnings("all")
public class LoginServiceImpl extends ServiceImpl<UserMapper, User> implements LoginService {

    @Resource
    private UserMapper userMapper;

    /**
     * 登录
     *
     * @param user
     * @return
     */
    @Override
    public Result<?> login(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", user.getUsername());
        queryWrapper.eq("password", user.getPassword());
        User res = userMapper.selectOne(queryWrapper);
        if (res == null) {
            return Result.error(-1, "用户名或密码错误");
        } else if (res.getStatus() == 2) {
            return Result.error(-2, "未通过审核，请联系管理员");
        }
        UserInfo info = new UserInfo(res);
        long token = System.currentTimeMillis();
        info.setToken(token);
        return Result.success(info);
    }

    /**
     * 注册
     * @param user
     * @return
     */
    @Override
    public Result<?> register(User user) {
     //先查询，再注册
        User res = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()));
        if (res != null) {
            return Result.error(-1, "该用户已存在，请重新注册账号");
        }

        user.setRegtime(new Date());
        user.setStatus(2);
        user.setSex("未知");
        userMapper.insert(user);
        return Result.success();
    }

    /**
     * 忘记密码
     * @param user
     * @return
     */
    //忘记密码
    @Override
    public Result<?> forget(User user) {
        User res = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()));

        if (res==null) {
            return Result.error(-2, "用户不存在,请前往注册");
        }
        res.setUsername(user.getUsername());
        res.setPassword(user.getPassword());
        userMapper.updateById(res);
        return Result.success();
    }

    /**
     * 重置密码
     * @param user
     * @return
     */
    //重置密码 默认为123456
    @Override
    public Result<?> reset(User user) {

        User res = userMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, user.getUsername()));
        if (res==null){
            return  Result.error(-2,"该用户不存在，请前往注册");
        }
        //res.setPassword(Md5.MD5("123456"));
        res.setPassword("123456");

        userMapper.updateById(res);
        return Result.success();
    }

}
